import {Component, KeyValueDiffers, ViewChild} from '@angular/core';

import {AlertController, ModalController, NavController, NavParams, ViewController, Platform} from 'ionic-angular';

import { Keyboard } from "@ionic-native/keyboard";
import { Content, LoadingController } from 'ionic-angular';

import {Common} from '../../../providers/common';

import {Storage} from '@ionic/storage';

import _ from 'lodash';
import {CoinService} from "./coin.service";
import {IpmCoinSelectStockNoModal} from "./selectStockNo.modal";
import * as moment from 'moment';
import {IpmCoinSelectDepositModal} from "./selectDeposit.modal";

@Component({
  selector: 'modal-ipm-coin-save-scene',
  templateUrl: './saveScene.html',
  providers: [CoinService]
})
export class IpmCoinSaveSceneModal{
	moa_page_name: any = "modal-ipm-coin-save-scene";
  moa_page_explain: any = "";

  PaperTradingType = "1";

  @ViewChild(Content) content: Content;

  dicData = {
    marketNoDic: [],
    investTypeDic: [],
    structuredFundList: [],
    sellChannelDic: []
  };

  saveEntity = null;
  showFieldEntity = null;

  stockCheckBox = "3";

  firstInputTime = 0;

  fundCode = "";
  planNo = "";
  isEdit = false;
  isAddData = false;

  isEditHG = false;

  focusZQPriceFlag = false;

  contentScrollTop = 0;

  position = null;
  addData = null;

  title = "";

  constructor(public alertCtrl: AlertController,
              public modalCtrl: ModalController,
              public navCtrl: NavController,
              private navParams: NavParams,
              public storage: Storage,
              public viewCtrl: ViewController,
              public coinService: CoinService,
              public common: Common,
              private differs:  KeyValueDiffers,
              public keyboard: Keyboard,
              public  plt: Platform,
              private loadingCtrl: LoadingController,
        ) {

    let isEdit = this.viewCtrl.getNavParams().get("isEdit");
    if (isEdit === true) {
      this.title = "修改模拟方案";
    } else {
      this.title = "新增模拟方案";
    }

    this.moa_page_explain = "货币基金试算 - " + this.title;

    this.fundCode = this.viewCtrl.getNavParams().get("fundCode");
    this.coinService.getPlanDic(this.fundCode).subscribe(dic => {
      console.log("getPlanDic().dic", dic);
      if (dic) {
        this.dicData.marketNoDic = dic.marketNoDic;
        this.dicData.investTypeDic = dic.investTypeDic;
        this.dicData.structuredFundList = dic.structuredFundList;
        this.dicData.sellChannelDic = dic.sellChannelDic;
      }
    });

    this.initSaveEntity();
  }

  ionViewDidLoad() {
    // this.app.setTitle('EmailSend');
    if (this.contentScrollTop === 0) {
      this.contentScrollTop = this.content.scrollTop;
    }

    /*/!**
     * 键盘显示触发
     *!/
    this.keyboard.onKeyboardShow().subscribe(data => {
      if (this.focusZQPriceFlag) {
        this.content.scrollTop = this.contentScrollTop;
        this.content.scrollTop = this.contentScrollTop + document.getElementById("tzType").offsetTop;
      }
    });

    /!**
     * 键盘关闭触发
     *!/
    this.keyboard.onKeyboardHide().subscribe(data => {
      this.focusZQPriceFlag = false;
    });*/

  }

  focusZQPrice() {
    console.log("focusZQPrice");
    this.focusZQPriceFlag = true;
  }

 
  initSaveEntity() {
    this.saveEntity = {
      "l_serial_no": {
        fieldName: "流水编号",
        fieldValue: "-1",
        notNull: true,
        isNumber: false
      },
      "l_plan_no": {
        fieldName: "方案编号",
        fieldValue: "",
        notNull: false,
        isNumber: false
      },
      "l_date": {
        fieldName: "流水生成日期",
        fieldValue: "",
        notNull: false,
        isNumber: false
      },
      "l_market_no": {
        fieldName: "市场代码",
        fieldValue: "",
        notNull: false,
        isNumber: false
      },
      "vc_stock_no": {
        fieldName: "证券代码",
        fieldValue: "",
        notNull: false,
        isNumber: false
      },
      "c_trade_flag": {
        fieldName: "交易标志",
        fieldValue: "",
        notNull: false,
        isNumber: false
      },
      "l_currency_no": {
        fieldName: "货币代码",
        fieldValue: "",
        notNull: false,
        isNumber: false
      },
      "c_invest_type": {
        fieldName: "投资类型",
        fieldValue: "",
        notNull: false,
        isNumber: false
      },
      "l_clear_speed": {
        fieldName: "清算速度",
        fieldValue: "",
        notNull: false,
        isNumber: false
      },
      "l_begin_date": {
        fieldName: "业务开始日期",
        fieldValue: "",
        notNull: true,
        isNumber: false
      },
      "l_end_date": {
        fieldName: "业务结束日期",
        fieldValue: "",
        notNull: true,
        isNumber: false
      },
      "l_busin_term": {
        fieldName: "业务期限",
        fieldValue: "",
        notNull: true,
        isNumber: false
      },
      "l_current_quantity": {
        fieldName: "发生数量",
        fieldValue: "",
        notNull: true,
        isNumber: true
      },
      "en_current_balance": {
        fieldName: "发生金额",
        fieldValue: "",
        notNull: true,
        isNumber: true
      },
      "en_current_fee": {
        fieldName: "发生费用",
        fieldValue: "",
        notNull: true,
        isNumber: true
      },
      "en_current_interest": {
        fieldName: "发生利息",
        fieldValue: "",
        notNull: true,
        isNumber: true
      },
      "en_net_price": {
        fieldName: "净价价格",
        fieldValue: "",
        notNull: true,
        isNumber: true
      },
      "en_full_price": {
        fieldName: "全价价格",
        fieldValue: "",
        notNull: true,
        isNumber: true
      },
      "en_yield": {
        fieldName: "收益率",
        fieldValue: "",
        notNull: true,
        isNumber: true
      },
      "vc_counter_party": {
        fieldName: "交易对手",
        fieldValue: "",
        notNull: true,
        isNumber: false
      },
      "vc_related_no": {
        fieldName: "关联代码",
        fieldValue: "",
        notNull: true,
        isNumber: false
      },
      "l_bond_count": {
        fieldName: "品种数量",
        fieldValue: "",
        notNull: true,
        isNumber: true
      },
      "c_clear_type": {
        fieldName: "结算机构类型",
        fieldValue: "",
        notNull: true,
        isNumber: false
      },
      "l_subfund_no": {
        fieldName: "分级基金代码",
        fieldValue: "",
        notNull: true,
        isNumber: false
      },
      "vc_net_id": {
        fieldName: "销售渠道",
        fieldValue: "",
        notNull: true,
        isNumber: false
      }
    };

    this.showFieldEntity = {
      vc_stock_name: "",
      vc_stock_type_name: "",
      after_tax_en_yield: "",
      en_current_balance: "",
      end_date_price: "",
      old_end_date_price: "",
      bank_name: "",
      chinese_money: "",
      vc_stock_no_short: ""
    };

    this.stockCheckBox = "3";

    this.saveEntity.l_date.fieldValue = this.common.getNowFormatDate();
    this.saveEntity.l_begin_date.fieldValue = this.common.getNowFormatDate();
    this.saveEntity.l_end_date.fieldValue = this.common.getNowFormatDate();

    this.fundCode = this.viewCtrl.getNavParams().get("fundCode");
    this.planNo = this.viewCtrl.getNavParams().get("planNo");
    this.saveEntity.l_plan_no.fieldValue = this.planNo;
    this.saveEntity.l_currency_no.fieldValue = "1003";
    this.saveEntity.l_market_no.fieldValue = "1001";
    this.saveEntity.l_clear_speed.fieldValue = "1";
    this.saveEntity.c_invest_type.fieldValue = "1";

    let oldData = this.viewCtrl.getNavParams().get("oldData");
    if (oldData) {
      console.log("initSaveEntity().oldData", oldData);
      this.isEdit = true;
      let keys = _.keys(this.saveEntity);
      _.forEach(keys, key => {
        if (key === "l_date" || key === "l_begin_date" || key === "l_end_date") {
          this.saveEntity[key]["fieldValue"] = moment(oldData[key]).format("YYYY-MM-DD");
        } else {
          if (key === "l_clear_speed") {
            this.saveEntity[key]["fieldValue"] = _.replace(oldData[key], "T+", "");
          } else {
            this.saveEntity[key]["fieldValue"] = oldData[key];
            if (this.saveEntity[key]["isNumber"]) {
              this.saveEntity[key]["fieldValue"] = _.replace(this.saveEntity[key]["fieldValue"], /,/g, "");
              this.saveEntity[key]["fieldValue"] = parseFloat(this.saveEntity[key]["fieldValue"]);
              if (key === "en_current_balance" || key === "en_current_interest") {
                this.saveEntity[key]["fieldValue"] = this.saveEntity[key]["fieldValue"] / 10000;
                console.log("en_current_balance", this.saveEntity[key]["fieldValue"]);
              }
              if (key === "en_yield") {
                this.saveEntity[key]["fieldValue"] = (Math.round(this.saveEntity[key]["fieldValue"] * 100) / 100).toFixed(2);
              }
            }
          }
        }
      });

      this.showFieldEntity.vc_stock_name = oldData["vc_stock_name"];
      this.showFieldEntity.vc_stock_type_name = oldData["c_stock_type_name"];

      if (oldData["vc_trade_name"] === '债券买入' || oldData["vc_trade_name"] === '债券卖出') {
        this.PaperTradingType = "1";
        // this.saveEntity.en_yield.fieldValue = parseFloat(this.saveEntity.en_yield.fieldValue) * 100;
        this.priceChanged();
        this.countChineseMoeny("en_current_balance", 10000);
      }
      if (oldData["vc_trade_name"] === '正回购' || oldData["vc_trade_name"] === '逆回购') {
        this.PaperTradingType = "2";
        let temp_vc_stock_no_short = this.saveEntity.vc_stock_no.fieldValue.split("_");
        if (temp_vc_stock_no_short[1]) {
          this.showFieldEntity.vc_stock_no_short = temp_vc_stock_no_short[1];
        }
        this.saveEntity.en_current_interest.fieldValue = parseFloat(oldData["en_current_interest"]) / 10000;
        this.saveEntity["en_current_balance"]["fieldValue"] =
          parseFloat(this.saveEntity["en_current_balance"]["fieldValue"].toFixed(4));

        /*this.showFieldEntity.end_date_price = this.saveEntity.en_current_balance.fieldValue +
          this.saveEntity.en_current_interest.fieldValue;*/
        this.countChineseMoeny("en_current_balance", 10000);
        this.isEditHG = true;
        this.hgPriceInput();
      }
      if (oldData["vc_stock_name"] === '定期存款') {
        this.PaperTradingType = "3";
        // this.saveEntity.en_yield.fieldValue = parseFloat(this.saveEntity.en_yield.fieldValue) * 100;
        console.log("定期存款en_yield", this.saveEntity.en_yield.fieldValue);
        this.showFieldEntity.bank_name = oldData["bank_name"];
        this.countChineseMoeny("en_current_balance", 10000);
      }
      if (oldData["vc_trade_name"] === '开基申购' || oldData["vc_trade_name"] === '开基赎回') {
        this.PaperTradingType = "4";
        this.countChineseMoeny("en_current_balance", 10000);
      }

      console.log("initSaveEntity().saveEntity", this.saveEntity);
    }

    this.position = this.viewCtrl.getNavParams().get("position");
    this.addData = this.viewCtrl.getNavParams().get("addData");
    if (this.position && this.addData) {
      this.initAddDataFormPosition();
    }
  }

  /**
   * 初始化从持仓分析添加模拟情景的数据
   */
  initAddDataFormPosition() {
    console.log("addToSimulateScene>>>>>", this.position, this.addData);
    this.isAddData = true;
    if (this.position.type === "p1") {
      this.PaperTradingType = "1";
      this.showFieldEntity.vc_stock_no_short = this.addData["vc_stock_code"];
      this.showFieldEntity.vc_stock_name = this.addData["vc_stock_name"];
      this.showFieldEntity.vc_stock_type_name = this.addData["c_stock_type_name"];

      this.saveEntity.l_begin_date.fieldValue = moment(this.addData["l_date"]).format("YYYY-MM-DD");
      this.saveEntity.vc_stock_no.fieldValue = this.addData["l_market_no"] + "_" + this.addData["vc_stock_code"];
      this.saveEntity.c_trade_flag.fieldValue = "4";
      this.saveEntity.l_clear_speed.fieldValue = "0";
      this.saveEntity.c_invest_type.fieldValue = this.addData["c_invest_type"];
      this.saveEntity.l_market_no.fieldValue = this.addData["l_market_no"];
      this.saveEntity.l_current_quantity.fieldValue = this.addData["en_td_quantity"];
    }
    if (this.position.type === "p2") {
      this.PaperTradingType = "3";
      this.saveEntity.c_trade_flag.fieldValue = "i";
      this.saveEntity.l_date.fieldValue = moment(this.addData["l_date"]).format("YYYY-MM-DD");
    }
  }

  close() {
    this.viewCtrl.dismiss("close");
  }

  selectStockNo(type) {
    let profileModal = this.modalCtrl.create(IpmCoinSelectStockNoModal, {
      marketNo: this.saveEntity.l_market_no.fieldValue,
      stockClass: type,
      stockCode: this.showFieldEntity.vc_stock_no_short
    });
    profileModal.onDidDismiss(data => {
      if (data && data != "close") {
        console.log(data);
        this.saveEntity.vc_stock_no.fieldValue = data["vc_stock_no"];
        this.saveEntity.c_trade_flag.fieldValue = "3";
        this.showFieldEntity.vc_stock_name = data["vc_stock_name"];
        this.showFieldEntity.vc_stock_type_name = data["vc_stock_type_name"];
        this.showFieldEntity.vc_stock_no_short = data["vc_stock_code"];
        if (this.PaperTradingType === "2") {
          this.saveEntity.c_trade_flag.fieldValue = "5";
          if (data["vc_full_name"] != "") {
            let params = {
              "l_date": moment(this.saveEntity.l_begin_date.fieldValue).format("YYYYMMDD"),
              "l_day": data["vc_full_name"],
            };
            this.coinService.postTRA_002_0051(params).subscribe(TRA_002_0051 => {
              if (TRA_002_0051 && TRA_002_0051[0]) {
                this.saveEntity.l_end_date.fieldValue = moment(TRA_002_0051[0]["l_trade_date"]).format("YYYY-MM-DD");
                // this.saveEntity.l_busin_term.fieldValue = parseInt(data["vc_full_name"]);
                this.saveEntity.l_busin_term.fieldValue =
                  _.toString(moment(this.saveEntity.l_end_date.fieldValue).diff(moment(this.saveEntity.l_begin_date.fieldValue)) / 1000 / 60 / 60 / 24);
              }
            });
            /*this.saveEntity.l_end_date.fieldValue =
              moment(this.saveEntity.l_begin_date.fieldValue).add(parseInt(data["vc_full_name"]), "day").format("YYYY-MM-DD");*/

          }
        }
      }
    });
    profileModal.present();
  }

  priceChanged() {
    console.log("priceChanged");

    if (!this.saveEntity.vc_stock_no.fieldValue) {
      this.common.alertMessage("请先选择债券");
      if (this.stockCheckBox === "1") {
        this.saveEntity.en_net_price.fieldValue = "";
      }
      if (this.stockCheckBox === "2") {
        this.saveEntity.en_full_price.fieldValue = "";
      }
      if (this.stockCheckBox === "3") {
        this.saveEntity.en_yield.fieldValue = "";
      }
      return false;
    }

    if (this.firstInputTime === 0) {
      this.firstInputTime = new Date().getTime();
    } else {
      let currentInputTime = new Date().getTime();
      if (currentInputTime - this.firstInputTime <= 1000) {
        this.firstInputTime = currentInputTime;
        return false
      }
    }

    if (this.stockCheckBox === "1" && this.saveEntity.en_net_price.fieldValue === "") {
      return false;
    }
    if (this.stockCheckBox === "2" && this.saveEntity.en_full_price.fieldValue === "") {
      return false;
    }
    if (this.stockCheckBox === "3" && this.saveEntity.en_yield.fieldValue === "") {
      return false;
    }

    let params = {
      "fundCode": this.fundCode,
      "selectedRadio": this.stockCheckBox,
      "l_date": this.saveEntity.l_begin_date.fieldValue,
      "vc_stock_no": this.saveEntity.vc_stock_no.fieldValue,
      "en_net_price": this.saveEntity.en_net_price.fieldValue,
      "en_full_price": this.saveEntity.en_full_price.fieldValue,
      "en_yield": this.saveEntity.en_yield.fieldValue,
      "l_clear_speed": this.saveEntity.l_clear_speed.fieldValue
    };
    console.log("params", params);
    this.coinService.getStockPrice(params).subscribe(stockPrice => {
      this.firstInputTime = 0;
      console.log("stockPrice", stockPrice);
      if (stockPrice) {
        this.saveEntity.en_net_price.fieldValue = stockPrice["en_net_price"];
        this.saveEntity.en_full_price.fieldValue = stockPrice["en_full_price"];
        this.saveEntity.en_yield.fieldValue = stockPrice["en_yield"];
        this.showFieldEntity.after_tax_en_yield = stockPrice["after_tax_en_yield"];
        if (parseFloat(this.saveEntity.en_net_price.fieldValue) <= -1
          || parseFloat(this.saveEntity.en_full_price.fieldValue) <= -1) {
          this.common.alertMessage("当前证券已过到期日，请重新选择证券！");
          this.saveEntity.en_net_price.fieldValue = "";
          this.saveEntity.en_full_price.fieldValue = "";
          this.saveEntity.en_yield.fieldValue = "";
          this.showFieldEntity.after_tax_en_yield = "";
        } else {
          this.l_current_quantity_input();
        }
      } else {
        this.saveEntity.en_net_price.fieldValue = "";
        this.saveEntity.en_full_price.fieldValue = "";
        this.saveEntity.en_yield.fieldValue = "";
        this.showFieldEntity.after_tax_en_yield = "";

      }
    });
  }

  //保存试算方案
  savePlan() {
    console.log(this.saveEntity);
    let checkResult = this.checkData();
    if (checkResult.code != "0") {
      this.common.alertMessage(checkResult.msg);
      return false;
    }

    this.saveEntity.l_current_quantity.fieldValue =
      this.convertStringToNumber("l_current_quantity", this.saveEntity.l_current_quantity.fieldValue);
    this.saveEntity.en_current_balance.fieldValue =
      this.convertStringToNumber("en_current_balance", this.saveEntity.en_current_balance.fieldValue);
    this.saveEntity.en_current_fee.fieldValue =
      this.convertStringToNumber("en_current_fee", this.saveEntity.en_current_fee.fieldValue);
    this.saveEntity.en_current_interest.fieldValue =
      this.convertStringToNumber("en_current_interest", this.saveEntity.en_current_interest.fieldValue);
    this.saveEntity.en_net_price.fieldValue =
      this.convertStringToNumber("en_net_price", this.saveEntity.en_net_price.fieldValue);
    this.saveEntity.en_full_price.fieldValue =
      this.convertStringToNumber("en_full_price", this.saveEntity.en_full_price.fieldValue);
    this.saveEntity.en_yield.fieldValue =
      this.convertStringToNumber("en_yield", this.saveEntity.en_yield.fieldValue);
    this.saveEntity.l_bond_count.fieldValue =
      this.convertStringToNumber("l_bond_count", this.saveEntity.l_bond_count.fieldValue);

    if (this.PaperTradingType === "2") {
      this.saveEntity.c_invest_type.fieldValue = "1";
    }

    if (this.PaperTradingType === "3") {
      this.saveEntity.c_invest_type.fieldValue = "1";
      this.saveEntity.l_market_no.fieldValue = "1099";
      this.saveEntity.vc_stock_no.fieldValue = "1099_870870";
      this.saveEntity.l_clear_speed.fieldValue = "0";
      // this.saveEntity.en_yield.fieldValue = _.toString(parseFloat(this.saveEntity.en_yield.fieldValue) / 100);
    }

    if (this.PaperTradingType === "4") {
      this.saveEntity.c_invest_type.fieldValue = "1";
      this.saveEntity.l_market_no.fieldValue = "1099";
      this.saveEntity.l_clear_speed.fieldValue = "0";
      let tempFund = _.find(this.dicData.structuredFundList,
        {"l_subfund_no": this.saveEntity.l_subfund_no.fieldValue});
      if (tempFund) {
        this.saveEntity.vc_stock_no.fieldValue = "1099_" + tempFund["l_fund_no"];
      }
    }

    let keys = _.keys(this.saveEntity);
    let params = {};
    _.forEach(keys, key => {
      if (key === "l_date" || key === "l_begin_date" || key === "l_end_date") {
        params[key] = _.replace(this.saveEntity[key].fieldValue, /-/g, "");
      } else {
        params[key] = this.saveEntity[key].fieldValue;
      }
    });
    console.log("savePlan.params", params);

    if (this.PaperTradingType === "1") {
      params["l_end_date"] = params["l_begin_date"];
    }
    let loading = this.loadingCtrl.create({
      content: "保存中...",
    });
    loading.present();
    this.coinService.savePlan(params).subscribe(result => {
      console.log(result);
      loading.dismiss();
      let alert = this.alertCtrl.create({
        title: "提示",
        message: '保存成功',
        buttons: [
          {
            text: '确定',
            role: 'cancel',
            handler: () => {
              //console.log('Cancel clicked');
            }
          }
        ]
      });
      alert.present();
      setTimeout(function(){
        alert.dismiss();
      }, 1000)
     
      this.viewCtrl.dismiss({
        isSuccess: true
      });
    });
  }

  checkData() {
    let result = {
      code: "0",
      msg: ""
    };
    switch (this.PaperTradingType) {
      case "1":
        if (!this.saveEntity.vc_stock_no.fieldValue) {
          result.msg = "债券代码不能为空！";
          result.code = "1";
          return result;
        }
        if (!this.saveEntity.en_net_price.fieldValue
          && !this.saveEntity.en_net_price.fieldValue
          && !this.saveEntity.en_net_price.fieldValue) {
          result.code = "1";
          result.msg = "净价、全价、收益率不能全部为空！";
          return result;
        }
        if (!this.saveEntity.c_clear_type.fieldValue) {
          result.code = "1";
          result.msg = "结算机构类型不能为空！";
          return result;
        }
        break;
      case "2":
        if (!this.saveEntity.vc_stock_no.fieldValue) {
          result.msg = "请选择交易品种";
          result.code = "1";
          return result;
        }
        break;
      case "3":
        break;
      case "4":
        break;
    }
    return result;
  }

  convertStringToNumber(key, fieldValue) {
    let rate = 1;
    if (fieldValue && fieldValue != "") {
      if (key === "en_current_balance" || key === "en_current_interest") {
        rate = 10000;
      }
      if (key === "en_yield") {
        rate = 0.01;
      }
      return parseFloat(fieldValue) * rate;
    } else {
      return "";
    }
  }

  l_current_quantity_input() {
    if (this.saveEntity.l_current_quantity.fieldValue && this.saveEntity.l_current_quantity.fieldValue != "") {
      this.saveEntity.en_current_balance.fieldValue = parseFloat(this.saveEntity.en_net_price.fieldValue) *
          parseFloat(this.saveEntity.l_current_quantity.fieldValue) / 10000;
      this.saveEntity.en_current_balance.fieldValue = _.toString(this.saveEntity.en_current_balance.fieldValue.toFixed(4));
      console.log(this.saveEntity.en_current_balance.fieldValue);
      this.countChineseMoeny("en_current_balance", 10000);
    }
  }

  countChineseMoeny(fieldName, rate) {
    if (rate) {
      if (typeof this.saveEntity[fieldName].fieldValue === "string") {
        this.showFieldEntity.chinese_money =
          this.common.changeMoneyToChinese(_.toString((parseFloat(this.saveEntity[fieldName].fieldValue) * rate).toFixed(4)));
      } else {
        this.showFieldEntity.chinese_money =
          this.common.changeMoneyToChinese(_.toString((this.saveEntity[fieldName].fieldValue * rate).toFixed(4)));
      }
    } else {
      this.showFieldEntity.chinese_money = this.common.changeMoneyToChinese(this.saveEntity[fieldName].fieldValue);
    }
  }

  paperTradingTypeChanged() {
    this.initSaveEntity();
    switch (this.PaperTradingType) {
      case "1":
        break;
      case "2":
        this.saveEntity.l_clear_speed.fieldValue = "0";
        this.saveEntity.l_busin_term.fieldValue = 0;
        break;
      case "3":
        this.saveEntity.c_trade_flag.fieldValue = "F";
        break;
      case "4":
        if (this.dicData.structuredFundList[0]) {
          this.saveEntity.l_subfund_no.fieldValue = this.dicData.structuredFundList[0]["l_subfund_no"];
        }
        if (this.dicData.sellChannelDic[0]) {
          this.saveEntity.vc_net_id.fieldValue = this.dicData.sellChannelDic[0]["vc_item_no"];
        }
        this.saveEntity.c_trade_flag.fieldValue = "p";
        break;
    }
  }

  /**
   * 回购的交易日期及到期日期变化执行方法
   */
  buyBackDateChange() {
    let beginDate = this.saveEntity.l_begin_date.fieldValue;
    let endDate = this.saveEntity.l_end_date.fieldValue;
    if (beginDate && endDate) {
      if (beginDate > endDate) {
        this.common.alertMessage("交易日期不能大于到期日期");
        this.saveEntity.l_end_date.fieldValue = this.saveEntity.l_begin_date.fieldValue;
      } else {
        this.saveEntity.l_busin_term.fieldValue = _.toString(moment(endDate).diff(moment(beginDate)) / 1000 / 60 / 60 / 24);
      }
    }
  }

  hgPriceInput() {
    this.countChineseMoeny("en_current_balance", 10000);

    if (this.saveEntity.vc_stock_no.fieldValue
      && this.saveEntity.en_current_balance.fieldValue
      && this.saveEntity.en_yield.fieldValue) {

      let params = {
        vc_stock_no: this.saveEntity.vc_stock_no.fieldValue,
        l_day_num: this.saveEntity.l_busin_term.fieldValue,
        en_banlance: (parseFloat(this.saveEntity.en_current_balance.fieldValue)),
        en_yield: (parseFloat(this.saveEntity.en_yield.fieldValue))
      };

      this.coinService.getHGPrice(params).subscribe(hgPrice => {
        console.log("getHGPrice().hgPrice", hgPrice);
        if (hgPrice && hgPrice[0]) {
          if (!this.isEditHG) {
            this.showFieldEntity.end_date_price = (parseFloat(hgPrice[0]["en_hg_balance"])).toFixed(4);
            this.showFieldEntity.old_end_date_price = (parseFloat(hgPrice[0]["en_hg_balance"])).toFixed(4);
            this.saveEntity.en_current_interest.fieldValue = (parseFloat(hgPrice[0]["en_hg_gain"])).toFixed(4);
          } else {
            this.showFieldEntity.end_date_price = (parseFloat(hgPrice[0]["en_hg_balance"]));
            this.showFieldEntity.old_end_date_price = (parseFloat(hgPrice[0]["en_hg_balance"]));
            this.isEditHG = false;
            this.input_hgsy();
          }
        }
      });
    }

  }

  input_hgsy() {
    if (this.showFieldEntity.end_date_price) {
      if (this.saveEntity.en_current_interest.fieldValue) {
        this.showFieldEntity.end_date_price = (parseFloat(this.showFieldEntity.old_end_date_price)
        + parseFloat(this.saveEntity.en_current_interest.fieldValue)).toFixed(4);
      } else {
        this.showFieldEntity.end_date_price = parseFloat(this.showFieldEntity.old_end_date_price).toFixed(4);
      }
    }

  }

  hg_l_current_quantity_input() {
    if (this.saveEntity.l_bond_count.fieldValue) {
      let params = {
        "fundCode": this.fundCode,
        "l_busin_flag": this.saveEntity.c_trade_flag.fieldValue,
        "l_market_no": this.saveEntity.l_market_no.fieldValue,
        "vc_stock_no": this.saveEntity.vc_stock_no.fieldValue,
        "l_current_quantity": this.saveEntity.l_current_quantity.fieldValue,
        "en_current_balance": this.saveEntity.en_current_balance.fieldValue * 10000,
        "en_bond_price": this.showFieldEntity.end_date_price * 10000,
        "l_bond_count": this.saveEntity.l_bond_count.fieldValue,
      };

      params["l_bond_count"] = params["en_current_balance"] / 100;
      params["l_current_quantity"] = params["en_current_balance"] / 100;

      console.log("hg_l_current_quantity_input().params", params);
      this.coinService.getPoundageFee(params).subscribe(poundageFee => {
        console.log("getPoundageFee", poundageFee);
        if (poundageFee && poundageFee[0]) {
          this.saveEntity.en_current_fee.fieldValue = parseFloat(poundageFee[0]["en_trade_fee"]).toFixed(4);
        }
      });
    }
  }

  dc_en_yield_input() {
    if (this.saveEntity.en_yield.fieldValue) {
      this.saveEntity.en_yield.fieldValue = parseFloat((Math.round(this.saveEntity.en_yield.fieldValue
        * 10000) / 10000).toFixed(4));
    }
  }

  selectDeposit() {
    let type = "bank";
    if (this.saveEntity.c_trade_flag.fieldValue === "F") {
      type = "bank";
    } else {
      type = "money";
    }
    let fundCode = this.viewCtrl.getNavParams().get("fundCode");
    let profileModal = this.modalCtrl.create(IpmCoinSelectDepositModal, {
      type: type,
      fundCode: fundCode
    });
    profileModal.onDidDismiss(data => {
      if (data && data != "close") {
        console.log(data);
        if (this.saveEntity.c_trade_flag.fieldValue === "F") {
          this.saveEntity.vc_related_no.fieldValue = data["l_bank_no"];
          this.showFieldEntity.bank_name = data["vc_bank_name"];
        } else {
          this.saveEntity.vc_related_no.fieldValue = data["vc_account_no"];
          this.saveEntity.en_current_balance.fieldValue = (parseFloat(data["en_balance"])
            - parseFloat(data["en_advance_balance"])) / 10000;
          this.saveEntity.en_yield.fieldValue = parseFloat(data["en_advance_rate"]) * 100;
        }
      }
    });
    profileModal.present();
  }

  marketChange() {
    this.saveEntity.vc_stock_no.fieldValue = "";
    this.showFieldEntity.vc_stock_name = "";
    this.showFieldEntity.vc_stock_type_name = "";
  }

  priceRadioClick(type) {
    this.stockCheckBox = type;
    let textinput = document.getElementById("priceRadioClick_" + type).getElementsByTagName("input")[0];
    // console.log("priceRadioClick", document.getElementById("priceRadioClick_" + type).getElementsByTagName("input"));
    let temp = _.find(textinput.attributes, {localName: "disabled"});
    if (temp) {
      textinput.attributes.removeNamedItem("disabled");
    }
    textinput.focus();
  }

  en_current_balance_input() {
    if (this.saveEntity.en_current_balance.fieldValue) {
      this.saveEntity.en_current_balance.fieldValue = parseFloat((Math.round(this.saveEntity.en_current_balance.fieldValue
        * 10000) / 10000).toFixed(4));
    }
  }

  en_current_interest_input() {
    if (this.saveEntity.en_current_interest.fieldValue) {
      this.saveEntity.en_current_interest.fieldValue = parseFloat((Math.round(this.saveEntity.en_current_interest.fieldValue
        * 10000) / 10000).toFixed(4));
    }
  }

}
